package com.meiyu.live.tv.anchor;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Point;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.FrameLayout;

import com.android.volley.Response;
import com.meiyu.live.BaseActivity;
import com.meiyu.live.R;
import com.meiyu.live.comm.Constant;
import com.meiyu.live.net.param.BaseBodyParams;
import com.meiyu.live.net.param.CreateLiveRoomParams;
import com.meiyu.live.net.param.CreateRoomParams;
import com.meiyu.live.net.response.CreateRooomResponse;
import com.meiyu.live.net.response.LivePreResponse;
import com.meiyu.live.util.ToastUtil;
import com.meiyu.live.widget.NetLoadingDailog;

import java.io.IOException;

public class StartPlayActivity extends BaseActivity implements SurfaceHolder.Callback, View.OnClickListener {

    private Context context;
    private SurfaceView surfaceview;
    private SurfaceHolder surfaceholder;
    private Camera camera;
    private View btn_back, btn_startplay;
    private NetLoadingDailog loadingDailog;
    private static CreateLiveRoomParams params;
    private static Activity from;

    public static void start(Activity activity, CreateLiveRoomParams createLiveRoomParams) {
        Intent intent = new Intent(activity, StartPlayActivity.class);
        from = activity;
        params = createLiveRoomParams;
        from.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        setContentView(R.layout.activity_startlive);
        initView();
    }

    private void initView() {
        loadingDailog = new NetLoadingDailog(this);

        surfaceview = (SurfaceView) findViewById(R.id.surfaceview);
        surfaceholder = surfaceview.getHolder();
        surfaceholder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        surfaceholder.addCallback(StartPlayActivity.this);

        btn_back = findViewById(R.id.btn_back);
        btn_back.setOnClickListener(this);
        btn_startplay = findViewById(R.id.starlive);
        btn_startplay.setOnClickListener(this);
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        System.out.println("surfacecreated");
        //获取camera对象
        int cameraCount = 0;
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        cameraCount = Camera.getNumberOfCameras();//得到摄像头的个数
        for (int i = 0; i < cameraCount; i++) {
            Camera.getCameraInfo(i, cameraInfo);//得到每一个摄像头的信息
            //现在是后置，变更为前置
            if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {//代表摄像头的方位，CAMERA_FACING_FRONT前置      CAMERA_FACING_BACK后置
                camera = Camera.open(i);//打开当前选中的摄像头
                break;
            }
        }
        try {
            //设置预览监听
            camera.setPreviewDisplay(surfaceholder);
            Camera.Parameters parameters = camera.getParameters();

            if (this.getResources().getConfiguration().orientation
                    != Configuration.ORIENTATION_LANDSCAPE) {
                parameters.set("orientation", "portrait");
                camera.setDisplayOrientation(90);
                parameters.setRotation(90);
            } else {
                parameters.set("orientation", "landscape");
                camera.setDisplayOrientation(0);
                parameters.setRotation(0);
            }
            findBestPreviewSize(parameters);
            camera.setParameters(parameters);
            //启动摄像头预览
            camera.startPreview();

        } catch (IOException e) {
            e.printStackTrace();
            camera.release();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
        try {
            //摄像头画面显示在Surface上
            camera.setPreviewDisplay(surfaceHolder);
            updateCameraParameters();
            camera.startPreview();
        } catch (IOException e) {
            if (camera != null) camera.release();
            camera = null;
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        if (camera != null) {
            camera.stopPreview();
            camera.release();
            camera = null;
        }
    }

    private Camera.Size findBestPreviewSize(Camera.Parameters parameters) {
        DisplayMetrics dm = getResources().getDisplayMetrics();

        String previewSizeValueString = null;
        int diff = Integer.MAX_VALUE;
        previewSizeValueString = parameters.get("preview-size-values");

        if (previewSizeValueString == null) {
            previewSizeValueString = parameters.get("preview-size-value");
        }

        if (previewSizeValueString == null) {  // 有些手机例如m9获取不到支持的预览大小   就直接返回屏幕大小
            return camera.new Size(dm.widthPixels, dm.heightPixels);
        }
        int bestX = 0;
        int bestY = 0;

        final String[] previewSizeStrings = previewSizeValueString.split(",");
        for (String prewsizeString : previewSizeStrings) {
            prewsizeString = prewsizeString.trim();

            int dimPosition = prewsizeString.indexOf('x');
            if (dimPosition == -1) {
                continue;
            }

            int newX = 0;
            int newY = 0;

            try {
                newX = Integer.parseInt(prewsizeString.substring(0, dimPosition));
                newY = Integer.parseInt(prewsizeString.substring(dimPosition + 1));
            } catch (NumberFormatException e) {
                continue;
            }

            Point screenResolution = new Point(dm.widthPixels, dm.heightPixels);

            int newDiff = Math.abs(newX - screenResolution.x) + Math.abs(newY - screenResolution.y);

            if (newDiff == diff) {
                bestX = newX;
                bestY = newY;
                break;
            } else if (newDiff < diff) {
                if ((3 * newX) == (4 * newY)) {
                    bestX = newX;
                    bestY = newY;
                    diff = newDiff;
                }
            }
        }
        if (bestX > 0 && bestY > 0) {
            parameters.setPreviewSize(bestX, bestY);
//            parameters.setPreviewSize(dm.widthPixels, dm.heightPixels);
            return camera.new Size(bestX, bestY);
        }
        return null;
    }

    private void updateCameraParameters() {
        if (camera != null) {
            DisplayMetrics dm = getResources().getDisplayMetrics();

            Camera.Parameters p = camera.getParameters();

//            long time = new Date().getTime();
//            p.setGpsTimestamp(time);

//            Camera.Size pictureSize = findBestPictureSize(p);
//            p.setPictureSize(pictureSize.width, pictureSize.height);

            // Set the preview frame aspect ratio according to the picture size.
//            Camera.Size size = p.getPictureSize();
//            PreviewFrameLayout frameLayout = (PreviewFrameLayout) findViewById(R.id.layout_preview);
//            frameLayout.setAspectRatio((double) size.width / size.height);

            Camera.Size previewSize = findBestPreviewSize(p);
            p.setPreviewSize(previewSize.width, previewSize.height);

            camera.setParameters(p);

            int supportPreviewWidth = previewSize.width;
            int supportPreviewHeight = previewSize.height;

            int srcWidth = dm.widthPixels;
            int srcHeight = dm.heightPixels;

            float ratio0 = (float) srcWidth / (float) srcHeight;
            float ratio1 = (float) supportPreviewHeight / (float) supportPreviewWidth;
            if (ratio0 < ratio1) {
                int height = srcHeight;
                int width = (int) (srcHeight * ratio1);
                surfaceview.setLayoutParams(new FrameLayout.LayoutParams(width, height));
            } else {
                int width = srcWidth;
                int height = (int) (srcWidth / ratio1);
                surfaceview.setLayoutParams(new FrameLayout.LayoutParams(width, height));
            }
        }
    }

    @Override
    public void onClick(View view) {
        if (view == btn_back) {
            finish();
        } else if (view == btn_startplay) {
            startLive();
        }
    }

    private void startLive() {
        loadingDailog.loading();
        if (params != null) {
            request(params, CreateRooomResponse.class, new Response.Listener<CreateRooomResponse>() {
                @Override
                public void onResponse(CreateRooomResponse createRooomResponse) {
                    loadingDailog.dismissDialog();
                    if (createRooomResponse.getStatusCode() == Constant.StatusCode_Success) {
                        //跳转到直播界面之前要释放摄像头
                        if (camera != null) {
                            camera.stopPreview();
                            camera.release();
                            camera = null;
                        }
                        AnchorActivity.start(StartPlayActivity.this, createRooomResponse);
                        finish();
                        if (from != null) {
                            from.finish();
                        }
                    } else {
                        ToastUtil.show(createRooomResponse.getMsg());
                    }
                }
            });
        } else {
            BaseBodyParams b = new BaseBodyParams();
            b.setUrl(Constant.VERSION + Constant.UrlParams.LIVEPRE);
            request(b, LivePreResponse.class, new Response.Listener<LivePreResponse>() {
                @Override
                public void onResponse(LivePreResponse livePreResponse) {
                    loadingDailog.dismissDialog();
                    if (livePreResponse != null && livePreResponse.getStatusCode() == Constant.StatusCode_Success) {
                        request(new CreateRoomParams((int) livePreResponse.getId()),
                                CreateRooomResponse.class, new Response.Listener<CreateRooomResponse>() {
                                    @Override
                                    public void onResponse(CreateRooomResponse createRooomResponse) {
                                        if (createRooomResponse.getStatusCode() == Constant.StatusCode_Success) {
                                            //跳转到直播界面之前要释放摄像头
                                            if (camera != null) {
                                                camera.stopPreview();
                                                camera.release();
                                                camera = null;
                                            }
                                            AnchorActivity.start(StartPlayActivity.this, createRooomResponse);
                                            finish();
                                            if (from != null) {
                                                from.finish();
                                            }
                                        } else {
                                            ToastUtil.show(createRooomResponse.getMsg());
                                        }
                                    }
                                });

                    } else {
                        ToastUtil.show(livePreResponse.getMsg());
                    }
                }
            });
        }

    }


    @Override
    public void onError() {
        super.onError();
        loadingDailog.dismissDialog();
    }
}
